package game;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import java.text.DecimalFormat;

public class MatrixCell extends GameObject {
	
	public boolean clicked, selected;
	private Point2D initSourcePos;
	public String value;
	boolean clickPossible;
	Font font1 = new Font("Book Antiqua", Font.BOLD, 12);
	FontMetrics fm;
	public int fontWidth;
	DecimalFormat nf = new DecimalFormat("0.00");
	public int i, d;

	public MatrixCell(String image, Point2D position, Point2D size, Point2D sourcePosition, Point2D sourceSize, boolean clickPossible) {
		super(image, position, size, sourcePosition, sourceSize);
		// TODO Auto-generated constructor stub
		initSourcePos = sourcePosition;
		this.clickPossible = clickPossible;
		i = 0;
		d = 0;
	}

	public void update()
	{
		if (new Rectangle((int)getPosition().getX(), (int)getPosition().getY(),
				  		  (int)getSize().getX(), (int)getSize().getY()).contains(Mouse.getInstance().getPositionMouse().x, 
				  				  												 Mouse.getInstance().getPositionMouse().y))
		{
			this.setSourcePosition(new Point2D.Double(this.initSourcePos.getX() + this.getSourceSize().getX(), this.getSourcePosition().getY()));
			if (Mouse.getInstance().isMousePressed(MouseEvent.BUTTON1))
			{
				if (clickPossible)
				{
					clicked = true;
					Calculator.CheckSelected();
				}
			}
			else
				clicked = false;
		}
		else
		{
			this.setSourcePosition(new Point2D.Double(this.initSourcePos.getX(), this.getSourcePosition().getY()));
			clicked = false;
		}
		
		if (selected)
			this.setSourcePosition(new Point2D.Double(this.initSourcePos.getX() + this.getSourceSize().getX(), this.getSourcePosition().getY()));
	}
	
	public void draw(Graphics2D g2d)
	{
		
		super.draw(g2d);
		g2d.setFont(font1);
		g2d.setColor(Color.BLACK);
		
		
		
		if (value != null)
		{
			
			String valor = CalculateValue();
			fm = g2d.getFontMetrics();
			fontWidth = fm.stringWidth(valor);
			int posX = (int)((this.getPosition().getX() + this.getSize().getX()/2) - (fontWidth/2));
			int posY = (int)this.getPosition().getY() + 20;
			
			g2d.drawString(valor, posX, posY);
		}
	}
	
	public String CalculateValue()
	{
		String str = "";
		
		if (isInt1(Double.parseDouble(value)))
			if (value.contains("."))
				str = value.substring(0, value.indexOf("."));
			else
				str = "" + Integer.parseInt(value);
		else
			str = nf.format(Double.parseDouble(value));
		return str;
	}
	
		private static boolean isInt1(double x) {
		    return x % 1 == 0;
		}
}
